from flask import Flask, g
import os
from datetime import timedelta
from dotenv import load_dotenv
from config_utils import get_secret_key, get_session_timeout, get_users, get_config
from routes.auth import auth_bp
from routes.pages import pages_bp
from routes.search import search_bp
from routes.ai_assistant import ai_assistant_bp
from routes.movie import movie_bp
# 添加新的蓝图导入
from routes.users_admin import users_admin_bp
from routes.movies_admin import movies_admin_bp

# 导入数据库工具
from db_utils import DbUtil

# 加载环境变量
load_dotenv()

# 获取数据库实例
def get_db():
    """获取或创建 DbUtil 实例"""
    if 'db' not in g:
        g.db = DbUtil(db_name='sqlite_database', root_path=os.getcwd())
    return g.db

def create_app():
    app = Flask(__name__)
    app.secret_key = get_secret_key()
    app.permanent_session_lifetime = timedelta(seconds=get_session_timeout())
    
    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(pages_bp)
    app.register_blueprint(search_bp)
    app.register_blueprint(ai_assistant_bp)
    app.register_blueprint(movie_bp, url_prefix='/movie')
    
    # 注册新的管理蓝图
    app.register_blueprint(users_admin_bp)
    app.register_blueprint(movies_admin_bp)
    
    # 请求处理前，初始化数据库连接
    @app.before_request
    def before_request():
        get_db()
    
    # 请求结束后，关闭数据库连接（如果存在）
    @app.teardown_appcontext
    def close_db(error):
        if hasattr(g, 'db'):
            # 如果 DbUtil 类有 close 方法，取消下面的注释
            # g.db.close()
            pass
    
    return app

if __name__ == '__main__':
    # 确保templates目录存在
    if not os.path.exists('templates'):
        os.makedirs('templates')
    
    # 创建应用实例
    app = create_app()
    
    # 打印启动信息
    gemini_config = get_config('api.gemini')
    google_config = get_config('api.google')
    
    print(f"Gemini API Key: {gemini_config.get('api_key', '未设置')}")
    print(f"Gemini API URL: {gemini_config.get('url', '未设置')}")
    print(f"Gemini Model: {gemini_config.get('model', '未设置')}")
    print(f"Google API Key: {google_config.get('api_key', '未设置')}")
    print(f"Search Engine ID: {google_config.get('search_engine_id', '未设置')}")
    
    print("登录系统已启动，可用账户:")
    users = get_users()
    for username, password in users.items():
        print(f"- 用户名: {username}, 密码: {password}")
    
    # 启动应用
    app.run(debug=True) 